package main.com.votes.controller;

import main.com.votes.utils.ConnDB;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/Statistics")
public class Statistics extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Map<String, Integer> userVoteCount = new HashMap<>();
        Map<String, Integer> articleVoteCount = new HashMap<>();

        try (Connection conn = ConnDB.getConnection()) {
            // 获取用户投票统计
            String userVoteQuery = "SELECT u.username, COUNT(v.id) AS vote_count " +
                    "FROM vote v JOIN user u ON v.userid = u.id " +
                    "GROUP BY u.username order by COUNT(v.id) desc limit 6";
            try (PreparedStatement stmt = conn.prepareStatement(userVoteQuery);
                 ResultSet rs = stmt.executeQuery()) {
                while (rs.next()) {
                    userVoteCount.put(rs.getString("username"), rs.getInt("vote_count"));
                }
            }

            // 获取文章投票统计
            String articleVoteQuery = "SELECT a.title, COUNT(v.id) AS vote_count " +
                    "FROM vote v JOIN article a ON v.articleid = a.id " +
                    "GROUP BY a.title order by COUNT(v.id) desc limit 6";
            try (PreparedStatement stmt = conn.prepareStatement(articleVoteQuery);
                 ResultSet rs = stmt.executeQuery()) {
                while (rs.next()) {
                    articleVoteCount.put(rs.getString("title"), rs.getInt("vote_count"));
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        request.setAttribute("userVoteCount", userVoteCount);
        request.setAttribute("articleVoteCount", articleVoteCount);
        request.getRequestDispatcher("admin/statistics.jsp").forward(request, response);
    }
}
